package com.jishaokang.filter;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.jishaokang.cache.ResultCache;
import com.jishaokang.dao.ForbidUserDAO;
import com.jishaokang.dao.UserDAO;
import com.jishaokang.model.dto.ForbidUser;
import com.jishaokang.model.dto.PowerClass;
import com.jishaokang.model.dto.User;
import com.jishaokang.model.vo.UserVO;
import com.jishaokang.util.MaskWordUtil;
import com.jishaokang.util.SpringUtil;
import com.jishaokang.util.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@WebFilter(urlPatterns = "/api/examiner/*",filterName = "ExaminerFilter")
public class ExaminerFilter implements Filter {

    @Autowired
    private UserDAO userDAO;
    @Autowired
    private TokenUtil tokenUtil;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        if (userDAO == null) userDAO = (UserDAO) SpringUtil.getBean("userDAO");
        if (tokenUtil == null) tokenUtil = (TokenUtil) SpringUtil.getBean("tokenUtil");

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        BodyReaderHttpServletRequestWrapper myRequestWrapper;
        HttpServletRequest httpServletRequest = (HttpServletRequest) servletRequest;

        // 封装请求参数
        myRequestWrapper = new BodyReaderHttpServletRequestWrapper(httpServletRequest);

        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setCharacterEncoding("utf-8");
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.addHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
        response.addHeader("Content-Type" ,"application/json;charset=UTF-8");
        // 假定session中有userId
        String body = myRequestWrapper.sessionStream;

        String token = null;
        String regex = "\"token\": \"(.*?)\"";
        Matcher matcher = Pattern.compile(regex).matcher(body);
        while (matcher.find()) {
            token = matcher.group(1);
        }
        if (token == null){
            response.setHeader("Access-Control-Allow-Origin", "*");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(ResultCache.getDataError(300,"审核员未登录")));
            writer.flush();
            return ;
        }
        //验证token
        Integer userId = tokenUtil.getUserIdByToken(token);
        if (userId == null) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(ResultCache.getDataError(300,"审核员未登录")));
            writer.flush();
            return ;
        }
        UserVO user = userDAO.selectByUserId(userId);
        user.setPowerClass(new Gson().fromJson(user.getPower(),PowerClass.class));

        if (!user.getPowerClass().getAllExaminer().equals("allow")) {
            response.setHeader("Access-Control-Allow-Origin", "*");
            PrintWriter writer = response.getWriter();
            writer.write(JSON.toJSONString(ResultCache.getDataError(401,"您没有审核员权限")));
            writer.flush();
            return ;
        }

        filterChain.doFilter(myRequestWrapper, servletResponse);
    }

    @Override
    public void destroy() {
    }


}